﻿using System;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace WAMM.WebUI.Infrastructure {
    internal class ImageResult : ActionResult {
        public string ContentType { get; set; }

        public byte[] ImageBytes { get; set; }

        public string SourceFilename { get; set; }

        //This is used for times where you have a physical location
        public ImageResult(string sourceFilename, string contentType) {
            if (sourceFilename == null) {
                throw new ArgumentException("Required argument is null.", "sourceFilename");
            }
            if (contentType == null) {
                throw new ArgumentException("Required argument is null.", "contentType");
            }
            SourceFilename = sourceFilename;
            ContentType = contentType;
        }

        //This is used for when you have the actual image in byte form
        public ImageResult(byte[] sourceStream, string contentType) {
            if (sourceStream == null) {
                throw new ArgumentException("Required argument is null.", "sourceStream");
            }
            if (contentType == null) {
                throw new ArgumentException("Required argument is null.", "contentType");
            }
            ImageBytes = sourceStream;
            ContentType = contentType;
        }

        public override void ExecuteResult(ControllerContext context) {
            var response = context.HttpContext.Response;
            response.Clear();
            response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.ContentType = ContentType;
            //Check to see if this is done from bytes or physical location
            if (ImageBytes != null) {
                //todo - write ImageBytes directly to output stream
                using (var stream = new MemoryStream(ImageBytes)) {
                    stream.WriteTo(response.OutputStream);
                }
            }
            else {
                response.TransmitFile(SourceFilename);
            }
        }
    }
}